package com.fulihui.information.biz.job;

import com.fulihui.information.common.config.AppConst;
import org.near.toolkit.common.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.io.File;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时清理缓存目录图片
 * Created by LeeSon on 2016/12/27 0027.
 */
@Component
public class PeriodClear {
    @Autowired
    private AppConst                 appConst;
    private ScheduledExecutorService executorService;

    @PostConstruct
    public void init() {
        executorService = Executors.newScheduledThreadPool(1);

        executorService.scheduleAtFixedRate(() -> {
            try {
                long currentTime = System.currentTimeMillis();

                File dir = new File(appConst.getImgTmpDir());
                if (dir.isDirectory()) {
                    for (String fileName : dir.list()) {
                        File file = new File(appConst.getImgTmpDir() + File.separator + fileName);
                        if (currentTime - file.lastModified() >= 1000 * 60 * 5) {
                            //删除大于5分钟之前创建的文件
                            Log.info("清理文件:" + file.getAbsolutePath());
                            file.delete();
                        }
                    }
                }
            } catch (Exception e) {
                Log.error(e.getMessage(), e);
            }
        }, 0, 10, TimeUnit.MINUTES);
    }

    @PreDestroy
    public void destroy() {
        if (null != executorService) {
            executorService.shutdown();
        }
    }
}